/* ----------------------------------------------------------------------------------------------------------------
 *  Reactor
 * ----------------------------------------------------------------------------------------------------------------
 */
package pure.engine.idea 
{
	import pure.debug.Logger;
	import pure.engine.core.Origin;
	import pure.engine.system.ns_despair;
	
	use namespace ns_despair;
	
	/**
	 * 反应器
	 * [Author] - PURE
	 * 
	 */
public class Reactor extends Origin implements IReactor
{



	/**
	 * 开始实行
	 * 
	 * [Feature] - ① 反应开始至结束，并不马上移除，而是继续留在队列中
	 *             ② 有新的反应开始实行，移除上一反应，依此类推
	 *             ③ 需要突然中断反应时，需要对首项调用IReaction的breakOff方法
	 */
	public function start():void
	{
		var ro:ReactionObject;
		
		if (m_reactionQueue.length <= 0)
		{
			Logger.reportError(this, 'execute', '反应队列中没有项目');
		}
		
		if (m_started)
		{
			m_reactionQueue.shift();
		}
		else
		{
			m_started = true;
		}
		
		ro = m_reactionQueue[0];
		ro.item.execute(this, ro.params);
	}

	

	/**
	 * 加入反应项目到队列
	 * 
	 * [Param] - 反应项目
	 * [Param] - 反应参数
	 */
	public function addReaction(item:IReactionItem, ...args):void
	{
		var ro:ReactionObject;
		
		m_reactionQueue.push(ro = new ReactionObject());
		ro.item = item;
		ro.params = args;
	}
	
	
	/**
	 * 直接执行反应项目
	 * 
	 * [Param] - [item]  反应项目
	 * [Param] - [args]  反应参数
	 */
	public function react(item:IReactionItem, ...args):void
	{
		var ro:ReactionObject;
		
		if (m_started)
		{
			m_reactionQueue[0].item.breakOff();
			m_reactionQueue.length  = 0;
		}
		else
		{
			m_started = true;
		}
		
		m_reactionQueue.push(ro = new ReactionObject());
		ro.item = item;
		ro.params = args;
		ro.item.execute(this, ro.params);
	}
	
	
	/**
	 * 清空反应队列
	 */
	public function clearAllReaction():void
	{
		if (m_started)
		{
			m_reactionQueue[0].item.breakOff();
			m_started = false;
			m_reactionQueue.length  = 0;
		}
	}
	
	
	
	
	
	
	//======================
	// Member
	//======================
	
	
	ns_despair var m_reactionQueue:Vector.<ReactionObject> = new Vector.<ReactionObject>();
	
	ns_despair var m_started:Boolean;
	

}

}

import pure.engine.idea.IReactionItem

class ReactionObject
{
	
	
	public var item:IReactionItem;
	
	public var params:Array;
}